*-------------------------------------------------------------------------------
* TITLE: 5.appendix_tables.do
* DESCRIPTION: Master file to set directories and run all analyses
* VERSION: MP17.0
* DATE: 08/26/21 
*-------------------------------------------------------------------------------


**------------------------------------------------------------------------------
** SETTINGS
**------------------------------------------------------------------------------
global Out "${Output}/appendix"


**------------------------------------------------------------------------------
** TABLE C1: Exploiting Individual Thresholds in Estimating Short-Term Responses
** 	to the Asset Transfer - Placebo Specifications
**------------------------------------------------------------------------------


* define programs to find threshold --------------------------------------------

cap program drop findthrpoly_het
program define findthrpoly_het, rclass
	syntax varlist [if] [in], by(varname)
	
	local k2: word 1 of `varlist'
	local k1: word 2 of `varlist'
	
	tempvar k1_2 k1_3
	
	gen `k1_2' = `k1'^2
	gen `k1_3' = `k1'^3
	
	reg `k2' `k1' `k1_2' `k1_3' `by' `if' `in'
	
	local a1 = _b[_cons]
	local a2 = _b[_cons] + _b[`by']
	local b = _b[`k1'] - 1
	local c = _b[`k1_2']
	local d = _b[`k1_3']
	
	mata thrpoly(`a1', `b', `c', `d')
	return scalar thr_below = r(thr)
	
	mata thrpoly(`a2', `b', `c', `d')
	return scalar thr_above = r(thr)
end

cap mata mata drop thrpoly()
mata
	void thrpoly(real scalar a, real scalar b, real scalar c, real scalar d)
	{
		ss = polyroots((a, b, c, d))
		thr = Re(ss[2])
		st_numscalar("r(thr)", thr)
	}
end


* prepare dataset -------------------------------------------------------------

	* Define earnings potential as average cow returns at village level
tempfile cowR

use "$Data/PovertyTraps_analysis.dta", clear
keep if survey==1 & cows_no>0
gen cows_no2=cows_no^2
reg livestock_inc_tot cows_no cows_no2
predict cowMReturn, res
collapse (mean) cowMReturn, by(branchid spotno)
su cowMReturn,d
gen med_cowP=r(p50)
gen aboveM_cReturn=cowMReturn>med_cowP
save `cowR', replace


	* define sample 
use "$Data/PovertyTraps_analysis.dta", clear
keep if stup==1 & treat==1 & Lk1<=3

	* merge earnings potential
merge m:1 branchid spotno using `cowR'
drop if _merge==2
drop _merge


	* prepare variables
		*  savings rate in yr 2 (2009)
gen savRate=savings/(savings+(pce_total*hhsize_adult_eq))
su savRate if survey==2 & treat & stup, d
gen aboveyr2med = savRate>r(p50) if survey==2 & savRate!=.
bysort hhid5: egen aboveM_savRate2 = max(aboveyr2med)
gen savRate2_yr = savRate if survey==2
bysort hhid5: egen savRate2 = max(savRate2_yr)
drop aboveyr2med savRate2_yr

keep if survey==1

		* Anxiety
tab H_anxietyD, m
gen no_anxiety = 1-H_anxietyD

		* Any formal education
gen any_educ = resp_educ_years>0


* find heterogeneous thresholds ------------------------------------------------

global vars aboveM_cReturn aboveM_savRate2  no_anxiety any_educ 

	* regressions loop
foreach v of global vars {
	
	reg Lk3 c.Lk1##c.Lk1##c.Lk1  `v' 
	cap drop pred_`v'	
	predict pred_`v'

	findthrpoly_het Lk3 Lk1, by(`v')
	global khatLow_`v' = r(thr_above)
	global khatHigh_`v' = r(thr_below)

}

	* define individual thresholds 
foreach v of global vars {
	cap drop khatI_`v'
	cap drop abovekI_`v'
	cap drop abovekLow_`v'
	cap drop abovekHigh_`v'
	
	gen khatI_`v' = ${khatHigh_`v'} if `v'==0
	replace khatI_`v' = ${khatLow_`v'} if `v'==1
	gen abovekI_`v' = Lk1 > khatI_`v'
	
	gen abovekLow_`v' = Lk1>${khatLow_`v'}
	gen abovekHigh_`v' = Lk1>${khatHigh_`v'} 
}

	* define individual thresholds combined
cap drop Lk1_2
cap drop Lk1_3
gen Lk1_2 = Lk1^2
gen Lk1_3 = Lk1^3

reg Lk3 Lk1 Lk1_2 Lk1_3 ${vars} 
local a = _b[_cons]
local b = _b[Lk1]-1
local c = _b[Lk1_2]
local d = _b[Lk1_3]

tempvar intercept 
gen `intercept' = `a' if e(sample)
foreach v of global vars {
	local b_`v' = _b[`v']
	replace `intercept' = `intercept' + `b_`v'' if `v'==1	
}
levelsof `intercept', local(ints)
gen khatI_all =.
foreach i of local ints {
	mata thrpoly(`i', `b', `c', `d')
	replace khatI_all = r(thr) if `intercept'==`i'
}
gen abovekI_all = Lk1 > khatI_all 
		
* regressions ------------------------------------------------------------------
global regvars aboveM_cReturn aboveM_savRate2 no_anxiety any_educ
local estlist
foreach v of global regvars {
  	
	cap drop this_kLow 
	gen this_kLow = abovekLow_`v'
	label var this_kLow "above low threshold"
	
	cap drop this_kHigh 
	gen this_kHigh = abovekHigh_`v'
	label var this_kHigh "above high threshold"
		
		* placebo: high k
	reg deltaLk3 this_kLow this_kHigh if treat==1 & stup==1 & Lk1<=3 & `v'==0, robust
	eststo est_p_`v'


	local estlist `estlist' est_p_`v'
}	


esttab `estlist' ///
	using "${Out}/heterogeneous_thresholds_placebo.tex", ///
	varlabels(this_kLow "Above \$ \hat{k_L} \$" this_kHigh "Above \$ \hat{k_H} \$" _cons "Constant")  ///
	prehead("\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" "\begin{tabular}{l *{4}c } \hline\hline")	/// 
	fragment   substitute(\_ _) ///
	mtitles("Earnings Potential" "Savings Rate" "No Anxiety" "Any Education") ///
	prefoot("\hline \\ ") ///
	postfoot("\hline\hline \end{tabular} ") ///
	replace		
	
	
**------------------------------------------------------------------------------
** TABLE C2: Difference in Differences Estimates of Long-Run Dynamics: Additional
**	Outcomes
**------------------------------------------------------------------------------

	* define sample
use "$Data/PovertyTraps_analysis.dta", clear
keep if stup==1 & treat==1 & Lk1<=3

	* prepare variables: Assets in constant prices, other assets, per capita consumption, poverty headcount
gen aboveT=Lk1>=2.333

replace Qk = Qk * 1000
replace pAssets = pAssets * 1000
gen otherAssets = pAssets - cows_value - land_own_total_value

gen HHfoodcons = pce_food * hhsize_adult_eq

		/* NOTE:
			For the poverty headcount we convert Per Capita Expenditure to current USD at PPP.
			This requires 
		*/

gen pceUSD = pce_total

replace pceUSD=(pceUSD/19.4) if survey==1
replace pceUSD=(pceUSD/21.5)*1.149 if survey==2
replace pceUSD=(pceUSD/24.7)*1.331 if survey==3
replace pceUSD=(pceUSD/26.8)*1.706 if survey==4
replace pceUSD=(pceUSD/30.4)*2.124 if survey==5

gen below190 = (pceUSD/365) <= 1.9 if pceUSD!=.
		
	* regression loop
local vars Qk otherAssets pce_total pce_food below190 
local regs
foreach v of local vars {
	areg `v' i.survey##i.aboveT , a(subdistrict) robust
	est sto mod_`v'
	local regs `regs' mod_`v'
	
		* test dynamics
	test 2.survey_wave#1.aboveT = 3.survey_wave#1.aboveT
	local test3 = r(p)
	test 2.survey_wave#1.aboveT = 4.survey_wave#1.aboveT
	local test4 = r(p)
	test 2.survey_wave#1.aboveT = 5.survey_wave#1.aboveT
	local test5 = r(p)
	
	
	foreach t in 3 4 5 {
	    if `test`t''<0.01 {
		    local tout`t' = "\$ < 0.01 \$"
		}
		else {
		    local tout`t' = string(`test`t'', "%6.3f")
		}
			
		estadd local test`t' "`tout`t''"
	}
}

 	* output table
esttab `regs' using "${Out}/LongTerm_additional.tex"	///
		, cells("b(star fmt(%12.0fc) pattern(1 1 1 1  0)) b(star fmt(%12.4fc) pattern(0 0 0  0 1)) " ///
		"se(par fmt(%12.0fc) pattern(1 1 1 1 0)) se(par fmt(%12.4fc) pattern(0 0 0 0 1)) " ) 	///		
		keep( 2.survey_wave#1.aboveT 3.survey_wave#1.aboveT 4.survey_wave#1.aboveT 5.survey_wave#1.aboveT) ///
		nonote  collabels( ,none) starlevels("*" 0.10 "**" 0.05 "***" 0.01) ///
		mlabels("Productive assets (constant prices)" "Other Assets" "Per-capita expenditure" "Per-capita food expenditure" "Below 1.90 USD/day" ) ///
		varlabels( 2.survey_wave#1.aboveT "Year 2 \$\times \$ above \$ \hat{k} \$" 3.survey_wave#1.aboveT "Year 4 \$\times \$ above \$ \hat{k} \$" 4.survey_wave#1.aboveT "Year 7 \$\times \$ above \$ \hat{k} \$" 5.survey_wave#1.aboveT "Year 11 \$\times \$ above \$ \hat{k} \$" ) ///
		scalars("test3 p-value year 2 vs. 4" "test4 p-value year 2 vs. 7" "test5 p-value year 2 vs. 11") ///
		prehead("\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" "\begin{tabularx}{\textwidth}{l *6{>{\centering\arraybackslash}X}  } \hline\hline") ///
		fragment ///
		prefoot("\hline") ///																									
		postfoot("\hline\hline \end{tabularx} ") ///
		replace		


		
**------------------------------------------------------------------------------
** TABLE C3: Difference in Differences Estimates of Long-Run Dynamics, Household
**	Fixed Effects
**------------------------------------------------------------------------------

	* define sample
use "$Data/PovertyTraps_analysis.dta", clear
keep if stup==1 & treat==1 & Lk1<=3

	* prepare variables
gen aboveT=Lk1>=2.34 
replace pAssets = pAssets * 1000
gen HHconsumption = pce_total * hhsize_adult_eq
gen HHfoodcons = pce_food * hhsize_adult_eq
gen sh=(livestock_hours_tot + hhlandcult_hours_tot)

	* regression loop
estimates clear	
local vars pAssets cows_value land_own_total_value HHconsumption income_resp_total selfemp_inc_tot total_hours_work sh
local regs
foreach v of local vars {
	
	areg `v' i.survey##i.aboveT, a(hhid5) robust coeflegend
	est sto mod_`v'
	local regs `regs' mod_`v'
	
	* test dynamics
	test 2.survey_wave#1.aboveT = 3.survey_wave#1.aboveT
	local test3 = r(p)
	test 2.survey_wave#1.aboveT = 4.survey_wave#1.aboveT
	local test4 = r(p)
	test 2.survey_wave#1.aboveT = 5.survey_wave#1.aboveT
	local test5 = r(p)
	
	
	foreach t in 3 4 5 {
	    if `test`t''<0.01 {
		    local tout`t' = "\$ < 0.01 \$"
		}
		else {
		    local tout`t' = string(`test`t'', "%6.3f")
		}
			
		estadd local test`t' "`tout`t''"
	}
	
}
 
 	* output table
esttab `regs' using "${Out}/LongTerm_hhFE.tex"	///
		, cells(" b(star fmt(%12.0fc))"  	///
				" se(par fmt(%12.0fc))" ) 	///
		keep( 2.survey_wave#1.aboveT 3.survey_wave#1.aboveT 4.survey_wave#1.aboveT 5.survey_wave#1.aboveT) ///
		nonote  collabels( ,none) starlevels("*" 0.10 "**" 0.05 "***" 0.01) ///
		mlabels("Productive assets" "Cows" "Land" "Cons." "Net Earnings" "Net Earnings self-empl." "Total hours" "Hours self-empl." ) ///
		varlabels( 2.survey_wave#1.aboveT "Year 2 \$\times \$ above \$ \hat{k} \$" 3.survey_wave#1.aboveT "Year 4 \$\times \$ above \$ \hat{k} \$" 4.survey_wave#1.aboveT "Year 7 \$\times \$ above \$ \hat{k} \$" 5.survey_wave#1.aboveT "Year 11 \$\times \$ above \$ \hat{k} \$" ) ///
		scalars("test3 p-value year 2 vs. 4" "test4 p-value year 2 vs. 7" "test5 p-value year 2 vs. 11") ///
		prehead("\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" "\begin{tabularx}{\textwidth}{l *8{>{\centering\arraybackslash}X}  } \hline\hline")			/// 
		fragment ///
		prefoot("\hline") ///																									
		postfoot("\hline\hline \end{tabularx} ") ///
		replace		

**------------------------------------------------------------------------------
** TABLE C4: Difference in Differences Estimates of Long-Run Dynamics, in Balanced
** Panel
**------------------------------------------------------------------------------

	* define sample
use "$Data/PovertyTraps_analysis.dta", clear
keep if stup==1 & treat==1 & Lk1<=3

	* prepare variables
gen aboveT=Lk1>=2.34 
replace pAssets = pAssets * 1000
gen otherAssets = pAssets - cows_value - land_own_total_value
gen HHconsumption = pce_total * hhsize_adult_eq
gen HHfoodcons = pce_food * hhsize_adult_eq
gen sh=(livestock_hours_tot +hhlandcult_hours_tot)

 	* define balanced panel samples
local vars pAssets cows_value land_own_total_value HHconsumption income_resp_total selfemp_inc_tot total_hours_work sh
foreach v of local vars {
	bysort hhid5: egen num_`v' = count(`v' != .)
	gen bal_`v' = num_`v'==5
} 

	* regression loop
local vars pAssets cows_value land_own_total_value HHconsumption income_resp_total selfemp_inc_tot total_hours_work sh

local regs
foreach v of local vars {
	
	areg `v' i.survey##i.aboveT if bal_`v'==1, a(subdistrict) robust
	est sto mod_`v'
	local regs `regs' mod_`v'
	
	* test dynamics
	test 2.survey_wave#1.aboveT = 3.survey_wave#1.aboveT
	local test3 = r(p)
	cap test 2.survey_wave#1.aboveT = 4.survey_wave#1.aboveT
	local test4 = r(p)
	test 2.survey_wave#1.aboveT = 5.survey_wave#1.aboveT
	local test5 = r(p)
	
	
	foreach t in 3 4 5 {
	    if `test`t''<0.01 {
		    local tout`t' = "\$ < 0.01 \$"
		}
		else {
		    local tout`t' = string(`test`t'', "%6.3f")
		}
			
		estadd local test`t' "`tout`t''"
	}
	
}
 
 	* output table
esttab `regs' using "${Out}/LongTerm_all_balanced.tex"	///
		, cells(" b(star fmt(%12.0fc))"  	///
				" se(par fmt(%12.0fc))" ) 	///
		keep( 2.survey_wave#1.aboveT 3.survey_wave#1.aboveT 4.survey_wave#1.aboveT 5.survey_wave#1.aboveT) ///
		nonote  collabels( ,none) starlevels("*" 0.10 "**" 0.05 "***" 0.01) ///
		mlabels("Productive assets" "Cows" "Land" "Cons." "Net Earnings" "Net Earnings self-empl." "Total hours" "Hours self-empl." ) ///
		varlabels(2.survey_wave#1.aboveT "Year 2 \$\times \$ above \$ \hat{k} \$" 3.survey_wave#1.aboveT "Year 4 \$\times \$ above \$ \hat{k} \$" 4.survey_wave#1.aboveT "Year 7 \$\times \$ above \$ \hat{k} \$" 5.survey_wave#1.aboveT "Year 11 \$\times \$ above \$ \hat{k} \$" ) ///
		scalars("test3 p-value year 2 vs. 4" "test4 p-value year 2 vs. 7" "test5 p-value year 2 vs. 11") ///
		prehead("\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" "\begin{tabularx}{\textwidth}{l *8{>{\centering\arraybackslash}X}  } \hline\hline")			/// 
		fragment ///
		prefoot("\hline") ///																									
		postfoot("\hline\hline \end{tabularx} ") ///
		replace		


**------------------------------------------------------------------------------
** TABLE C5: Difference in Differences Estimates of Long-Run Dynamics, in small
** window around khat
**------------------------------------------------------------------------------

	* define sample
use "$Data/PovertyTraps_analysis.dta", clear
keep if stup==1 & treat==1 & Lk1<=3

	* prepare variables
gen aboveT=Lk1>=2.333 

replace pAssets = pAssets * 1000
gen HHconsumption = pce_total * hhsize_adult_eq
gen HHfoodcons = pce_food * hhsize_adult_eq
gen sh=(livestock_hours_tot +hhlandcult_hours_tot)

gen narrow = Lk1>2.233 & Lk1<2.433

	* regression loop
estimates clear	
local vars pAssets cows_value land_own_total_value HHconsumption income_resp_total selfemp_inc_tot total_hours_work sh
local regs
foreach v of local vars {
	
	areg `v' i.survey##i.aboveT if narrow, a(subdistrict) robust coeflegend
	est sto mod_`v'
	local regs `regs' mod_`v'
	
	* test dynamics
	test 2.survey_wave#1.aboveT = 3.survey_wave#1.aboveT
	local test3 = r(p)
	test 2.survey_wave#1.aboveT = 4.survey_wave#1.aboveT
	local test4 = r(p)
	test 2.survey_wave#1.aboveT = 5.survey_wave#1.aboveT
	local test5 = r(p)
	
	
	foreach t in 3 4 5 {
	    if `test`t''<0.01 {
		    local tout`t' = "\$ < 0.01 \$"
		}
		else {
		    local tout`t' = string(`test`t'', "%6.3f")
		}
			
		estadd local test`t' "`tout`t''"
	}
	
}
 
 	* output table
esttab `regs' using "${Out}/LongTerm_narrow.tex"	///
		, cells(" b(star fmt(%12.0fc))"  	///
				" se(par fmt(%12.0fc))" ) 	///
		keep( 2.survey_wave#1.aboveT 3.survey_wave#1.aboveT 4.survey_wave#1.aboveT 5.survey_wave#1.aboveT) ///
		nonote  collabels( ,none) starlevels("*" 0.10 "**" 0.05 "***" 0.01) ///
		mlabels("Productive assets" "Cows" "Land" "Cons." "Net Earnings" "Net Earnings self-empl." "Total hours" "Hours self-empl." ) ///
		varlabels( 2.survey_wave#1.aboveT "Year 2 \$\times \$ above \$ \hat{k} \$" 3.survey_wave#1.aboveT "Year 4 \$\times \$ above \$ \hat{k} \$" 4.survey_wave#1.aboveT "Year 7 \$\times \$ above \$ \hat{k} \$" 5.survey_wave#1.aboveT "Year 11 \$\times \$ above \$ \hat{k} \$" ) ///
		scalars("test3 p-value year 2 vs. 4" "test4 p-value year 2 vs. 7" "test5 p-value year 2 vs. 11") ///
		prehead("\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" "\begin{tabularx}{\textwidth}{l *8{>{\centering\arraybackslash}X}  } \hline\hline") /// 
		fragment ///
		prefoot("\hline") ///																									
		postfoot("\hline\hline \end{tabularx} ") ///
		replace		

	

**------------------------------------------------------------------------------
** TABLE C6: Life Cycle Effects and Long-Run Dynamics
**------------------------------------------------------------------------------

	* define sample
use "$Data/PovertyTraps_analysis.dta", clear
keep if stup==1 & treat==1 & Lk1<=3

	* prepare variables
gen aboveT=Lk1>=2.333

	* generage variables
replace pAssets = pAssets * 1000
gen HHconsumption = pce_total * hhsize_adult_eq
gen HHfoodcons = pce_food * hhsize_adult_eq
gen sh=(livestock_hours_tot +hhlandcult_hours_tot)

su resp_age if survey==1, d
gen above_med_age = age1 > r(p50) & age1!=.

	* regression loop
local vars pAssets cows_value land_own_total_value HHconsumption income_resp_total selfemp_inc_tot total_hours_work sh

local regs_below
local regs_above

foreach v of local vars {
    
		* test for young-old difference at year 11
	qui reg `v' i.survey##i.aboveT i.subdistrict if above_med_age==0 
	est sto m1_`v'
	qui reg `v' i.survey##i.aboveT i.subdistrict if above_med_age==1 
	est sto m2_`v'
	
	suest m1_`v' m2_`v', vce(robust)	
	
	forval t= 4/5 {
		test [m1_`v'_mean]`t'.survey_wave#1.aboveT = [m2_`v'_mean]`t'.survey_wave#1.aboveT

		local p`t'= r(p)
			if `p`t''<0.01 {
				local p`t'out = "$ <0.01$"	
			}
			else {
				  local  p`t'out = string(`p`t'', "%6.3f" ) 
			}			
	}
	
		* below median age
	areg `v' i.survey##i.aboveT  if above_med_age==0 , a(subdistrict) robust
	est sto b_`v'
	local regs_below `regs_below' b_`v'
	
		* above median age
	areg `v' i.survey##i.aboveT  if above_med_age==1 , a(subdistrict) robust
	est sto a_`v'	
	
	estadd local t4 "`p4out'"
	estadd local t5 "`p5out'"
	local regs_above `regs_above' a_`v'
	
}

 	* output table
esttab `regs_below' using "${Out}/LongTerm_byMage.tex"	///
		, cells(" b(star fmt(%12.0fc))"  	///
				" se(par fmt(%12.0fc))" ) 	///
		keep( 2.survey_wave#1.aboveT 3.survey_wave#1.aboveT 4.survey_wave#1.aboveT 5.survey_wave#1.aboveT) ///
		nonote  collabels( ,none) starlevels("*" 0.10 "**" 0.05 "***" 0.01) ///
		mlabels("Productive assets" "Cows" "Land" "Cons." "Net Earnings" "Net Earnings self-empl." "Total hours" "Hours self-empl." ) ///
		varlabels( 2.survey_wave#1.aboveT "Year 2 \$\times \$ above \$ \hat{k} \$" 3.survey_wave#1.aboveT "Year 4 \$\times \$ above \$ \hat{k} \$" 4.survey_wave#1.aboveT "Year 7 \$\times \$ above \$ \hat{k} \$" 5.survey_wave#1.aboveT "Year 11 \$\times \$ above \$ \hat{k} \$" ) ///
		prehead("\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" "\begin{tabularx}{\textwidth}{l *8{>{\centering\arraybackslash}X}  } \hline\hline")			/// 
		posthead(" &&& \\  \multicolumn{9}{l}{\textbf{Panel A: Below median age}} \\ \hline ") /// 
		fragment ///
		replace		
		
 esttab `regs_above' using "${Out}/LongTerm_byMage.tex"	///
		, cells(" b(star fmt(%12.0fc))"  	///
				" se(par fmt(%12.0fc))" ) 	///
		keep( 2.survey_wave#1.aboveT 3.survey_wave#1.aboveT 4.survey_wave#1.aboveT 5.survey_wave#1.aboveT) ///
		nonote  collabels( ,none) starlevels("*" 0.10 "**" 0.05 "***" 0.01) ///
		varlabels( 2.survey_wave#1.aboveT "Year 2 \$\times \$ above \$ \hat{k} \$" 3.survey_wave#1.aboveT "Year 4 \$\times \$ above \$ \hat{k} \$" 4.survey_wave#1.aboveT "Year 7 \$\times \$ above \$ \hat{k} \$" 5.survey_wave#1.aboveT "Year 11 \$\times \$ above \$ \hat{k} \$" ) ///
		nomtitles  nonumbers nolines ///
		scalars("t4  &&& \\ p-value old vs. young in year 7" "t5 p-value old vs. young in year 11") ///
		posthead(" &&& \\  \multicolumn{9}{l}{\textbf{Panel B: Above median age}} \\ \hline ") /// 
		fragment ///
 		prefoot("\hline") ///
		postfoot("\hline\hline \end{tabularx} ") ///		
		append		
		


